import subprocess
from config import Env

class RunnerControllor(object):
    def __init__(self):
        self.__runners = []  # fd->process object

    def add(self,runner):
        self.__runners.append(runner)

    def remove(self,runner):
        runner.exit()
        self.__runners.remove(runner)

    def start(self):
        for r in self.__runners:
            r.run()

    def stop(self):
        for r in self.__runners:
            r.exit()

    def get_all(self):
        return self.__runners

    def get_runner_by_fd(self,fd):
        for r in self.__runners:
            if r.fd == fd:
                return r


class Runable(object):
    '''
    命令执行
    '''
    def __init__(self,cmd):
        if cmd:
            self.__cmd = cmd
        else:
            raise Exception('cmd not correct:{}'.format(cmd))
        self.process = None

    def run(self):
        self.process = subprocess.Popen(self.__cmd,stdout=subprocess.PIPE)

    @property
    def fd(self):
        return self.process.stdout.fileno()

    def get_output(self):
        # return self.process.stdout.readlines()
        line =  self.process.stdout.readline()
        return line

    def exit(self):
        self.process.kill()

    @property
    def cmd(self):
        return self.__cmd


class Tailf(object):

    def __init__(self,path):
        self.__path = path
        self.__pos = 0
        self.__fd = None

    def run(self):
        if self.__fd is None:
            self.__fd = open(self.__path)

    def get_output(self):
        if self.__fd:
            self.fd.seek(self.__pos,0)
            out = self.__fd.read()
            self.__pos = self.__fd.tell()
            return out

    def exit(self):
        if self.__fd:
            self.__fd.close()

    @property
    def fd(self):
        if self.__fd:
            return self.__fd.fileno()
    @property
    def path(self):
        return self.__path



